import { ProForm } from '@ant-design/pro-components';
import { PlusOutlined } from '@ant-design/icons';
import '@toast-ui/editor/dist/toastui-editor.css';
import { Editor } from '@toast-ui/react-editor';
import { Form, Input, Select, Upload,Image, Row, Col, Space } from "antd";
import { useDispatch, useSelector } from '@umijs/max';
import { useEffect, useState, useRef } from "react";

export default function BookForm(props) {
    // 请求仓库数据
    const dispatch = useDispatch()
    const formRef = useRef()
    const editorRef = useRef()
    const [imageUrl, setImageUrl] = useState('')
    const { typeList } = useSelector(state => state.type)
    useEffect(() => {
        // 
        if (typeList.length === 0) {
            // 请求数据
            dispatch({
                type: 'type/_initList'
            })
        } else {
            console.log("已经有数据不用请求")
        }
    }, [])
    useEffect(() => {
        formRef.current.setFieldsValue(props.initData);
        // 如果是编辑模式需要设置编辑器里面的内容
        if (props.type === 'edit') {
            editorRef.current.getInstance().setHTML(props.initData.bookIntro)
        }

    }, [props.initData])
    const uploadButton = (
        <div>
            {<PlusOutlined></PlusOutlined>}
            <div
                style={{
                    marginTop: 8,
                }}
            >

            </div>
        </div>
    );
    const selectOption = typeList.map((item) => {
        return {
            value: item._id,
            label: item.typeName
        }
    })
    function handleFormFinish(data) {
        // 修改图片地址
        // 如果修改了图片就覆盖地址
        if(imageUrl!==''){
            data.bookPic = imageUrl;
        }
        // 处理markdown里面的内容
        const content = editorRef.current.getInstance().getHTML()
        data.bookIntro = content;
        props.submit({ ...data })


    }
    function handlePicChange(event) {
        if (event.file.status === 'done' && event.file.response.data) {
            setImageUrl(event.file.response.data)

        }
    }
    function validateIntro() {
        // 获取editor里面的内容
        const content = editorRef.current.getInstance().getHTML()
        const reg = /<[\/]?\w+>/g
        if (content.replaceAll(reg, '').trim() === '' || content.replaceAll(reg, '').trim() === '请填写书籍介绍') {
            return Promise.reject('请输入书籍介绍')
        } else {
            return Promise.resolve()
        }
    }
    function validatePoint(val) {
        if (isNaN(Number(val))) {
            return Promise.reject('请输入数字')
        }
        if (Number(val) % 1 !== 0) {
            return Promise.reject('请输入整数')
        }

        return Promise.resolve()

    }
    return (
        <ProForm
            formRef={formRef}
            submitter={{
                searchConfig: {
                    resetText: '重置',
                    submitText: props.type === 'add' ? '确认新增' : '确认编辑',
                },
                render: (props, doms) => {
                    console.log(props, doms)
                    // 交换位置
                    const temp = doms[0];
                    doms[0] = doms[1]
                    doms[1] = temp
                    return (
                        <Row>
                            <Col span={16} offset={2}>
                                <Space>{doms}</Space>
                            </Col>
                        </Row>
                    );
                },
            }}
            onFinish={handleFormFinish}
            layout="horizontal"
            labelCol={{
                span: 2,
            }}
            wrapperCol={{
                span: 20,
            }}
        >
            <Form.Item
                label="书籍标题"
                name="bookTitle"
                validateFirst={true}
                rules={[
                    {
                        required: true,
                        message: '请输入书籍标题',
                    },
                    // {
                    //     max: 10,
                    //     min: 4,
                    //     message: '长度在4-10之间',
                    // },
                    // ({ getFieldValue }) => ({
                    //     validator(_, value) {
                    //         return validateLoginId(value);
                    //     },
                    // }),
                ]}
            >
                <Input />
            </Form.Item>
            <Form.Item
                label="书籍介绍"
                name="bookIntro"
                rules={[
                    {
                        required: true, message: '请输入书籍介绍'
                    },
                    ({ getFieldValue }) => ({
                        validator(_, value) {
                            return validateIntro(value);
                        },
                    })
                ]}
            >
                <Editor
                    ref={editorRef}
                    initialValue="请填写书籍介绍"
                    previewStyle="vertical"
                    height="600px"
                    initialEditType="markdown"
                    useCommandShortcut={true} />
            </Form.Item>
            <Form.Item
                label="下载链接"
                name="downloadLink"
                rules={[
                    {
                        required: true,
                        message: '请输入下载链接',
                    },

                ]}
            >
                <Input />
            </Form.Item>
            <Form.Item
                label="所需积分"
                name="requirePoints"
                validateTrigger='onBlur'
                validateFirst={true}

                rules={[
                    {
                        required: true,
                        message: '请填写所需积分',
                    },
                    ({ getFieldValue }) => ({
                        validator(_, value) {
                            return validatePoint(value);
                        },
                    })

                ]}
            >
                <Input style={{
                    width: 200,
                }} />
            </Form.Item>
            <Form.Item
                label="书籍分类"
                name="typeId"

                rules={[
                    {
                        required: true,
                        message: '请选择书籍分类',
                    },


                ]}
            >
                <Select
                    style={{
                        width: 200,
                    }}

                    options={selectOption}
                />
            </Form.Item>
            {props.type === 'edit' ? (
                <Form.Item label="当前封面">
                    <Image width={150} src={props.initData.bookPic} />
                </Form.Item>
            ) : null}
            <Form.Item label="书籍封面" name="bookPic"
                rules={[
                    // {
                    //     required: true,
                    //     message: '请上传书籍封面',
                    // },


                ]}>
                <Upload
                    showUploadList={false}
                    onChange={handlePicChange}
                    className="avatar-uploader"
                    listType="picture-card"
                    action="/api/upload"
                    maxCount={1}
                >
                    {imageUrl !== '' ? (
                        <img
                            src={imageUrl}
                            alt="avatar"
                            style={{
                                width: '100%',
                            }}
                        />
                    ) : (
                        uploadButton
                    )}
                </Upload>
            </Form.Item>
        </ProForm>
    )
}